package com.cr.backbone.util;

import java.io.File;
import java.util.ArrayList;
import java.util.Map;

import javax.activation.DataSource;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.cr.backbone.model.SysFile;
import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;

/**
 * @project RaedNote
 * @version 1.0
 * @company 
 * @fileDescribe
 * @fileType UtilsSendMail UtilsSendMail.java
 * @author xianghua.hu
 * @date 2012-3-14 下午04:26:25
 */
public class UtilsSendMail  {
	

	private static UtilsSendMail instance=null;
	private JavaMailSender javaMailSender =null;
	
	public UtilsSendMail() {
		ClassPathXmlApplicationContext apx = new ClassPathXmlApplicationContext("spring/applicationContext-mail.xml");
		javaMailSender =(JavaMailSender)apx.getBean("mailSender");
	}
	
	public static UtilsSendMail getInstance(){
		if(instance ==null)
			instance=new UtilsSendMail();
		return instance;
	}

	/**
	 * 发送邮件
	 * @methodDescribe
	 * @param mailMessage
	 * @author xianghua.hu
	 * @date 2012-5-13 下午03:18:05
	 */
	public void sendMail(SimpleMailMessage mailMessage) {
		System.out.println("等待发送："+mailMessage.getSubject());
		try {
			javaMailSender.send(mailMessage );
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		    System.out.println("发送异常："+mailMessage.getSubject());

		}
	    System.out.println("发送完毕："+mailMessage.getSubject());
	}
	
	/**
	 * 发送HTML邮件
	 * @methodDescribe
	 * @param mailMessage
	 * @author xianghua.hu
	 * @date 2012-5-13 下午03:18:05
	 */
	public void sendMailHtml(MimeMessage mailMessage) {
		String mailSubjectString="null";
		try {
			if(mailMessage == null || mailMessage.isExpunged())
				throw new Exception("mail message is null");
			mailSubjectString=mailMessage.getSubject();
			System.out.println("等待发送html mail："+mailSubjectString);
			javaMailSender.send(mailMessage);
		} catch (Exception e) {
			e.printStackTrace();
		    System.out.println("发送异常html mail："+mailSubjectString);

		}
	    System.out.println("发送完毕html mail："+mailSubjectString);
	}
	
	/**
	 * 发送邮件
	 * @methodDescribe
	 * @param from	发送者
	 * @param to	接收者
	 * @param subject	标题
	 * @param text	内容
	 * @author xianghua.hu
	 * @date 2012-5-13 下午03:17:58
	 */
	public void sendMail(String from,String to,String subject,String text){
        SimpleMailMessage mailMessage=initSimpleMailMessage(from, to, subject, text);;
		sendMail(mailMessage);
//      System.out.println("spring mail send success!");
	}
	
	
	/**
	 * 发送邮件
	 * @methodDescribe
	 * @param from	发送者
	 * @param to	接收者
	 * @param subject	标题
	 * @param text	内容
	 * @author xianghua.hu
	 * @param paramsTemplate 
	 * @date 2012-5-13 下午03:17:58
	 */
	public void sendMailHtml(String from,String to,String subject,String textTemplate, Map<String, String> paramsTemplate){
        
		MimeMessage mailMessage=initMimeMailMessage(from, to, subject, textTemplate, paramsTemplate);
		sendMailHtml(mailMessage);
	}
	
	
	/**
	 * 发送邮件
	 * @methodDescribe
	 * @param from	发送者
	 * @param to	接收者
	 * @param subject	标题
	 * @param text	内容
	 * @author xianghua.hu
	 * @date 2012-5-13 下午03:17:58
	 */
	public void sendMailTestFromHuxianghua(String from,String to,String subject,String text){
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom("huxianghua_java@163.com");
        mailMessage.setTo("huxianghua@bfec.cn");
        mailMessage.setSubject("测试spring Mail");
        mailMessage.setText("hello,this is spring mail!\n i'm huxianghuahua.");
        sendMail(mailMessage);
        System.out.println("spring mail send success!");
	}
	
	/**
	 * init simple mail
	 * @methodDescribe
	 * @param from	发送者
	 * @param to	接收者
	 * @param subject	标题
	 * @param text	内容
	 * @return
	 * @author xianghua.hu
	 * @date 2012-5-13 下午03:30:03
	 */
	public SimpleMailMessage initSimpleMailMessage(String from,String to,String subject,String text){
		System.out.println("初始化邮件对象："+subject);
		SimpleMailMessage mailMessage = new SimpleMailMessage();
		from=UtilsConfigProperties.getInstance().getProperty(UtilsConfig.MAIL_FROM);//不论传入什么参数，获取系统参数
		mailMessage.setFrom(from);
        mailMessage.setTo(to);
        mailMessage.setSubject(subject);
        mailMessage.setText(text);
        return mailMessage;
        
	}
	
	
	/**
	 * init html mail by textTemplate/paramsTemplate
	 * @methodDescribe
	 * @param from	发送者
	 * @param to	接收者
	 * @param subject	标题
	 * @param text	内容
	 * @return
	 * @author xianghua.hu
	 * @date 2012-5-13 下午03:30:03
	 */
	public MimeMessage initMimeMailMessage(String from,String to,String subject,String textTemplate,Map<String, String> paramsTemplate){
		try {
			String text=UtilsTemplateFreemarker.getInstance().getMessage(textTemplate,paramsTemplate);
			MimeMessage mimeMessage = initMimeMailMessage(from, to, subject, text);
			return mimeMessage;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 * init html mail
	 * @methodDescribe
	 * @param from	发送者
	 * @param to	接收者
	 * @param subject	标题
	 * @param text	内容
	 * @return
	 * @author xianghua.hu
	 * @date 2012-5-13 下午03:30:03
	 */
	public MimeMessage initMimeMailMessage(String from,String to,String subject,String text){
		try {
			MimeMessage  mimeMessage = javaMailSender.createMimeMessage();
			MimeMessageHelper messageHelper =new MimeMessageHelper(mimeMessage, true, "GB2312");
			messageHelper.setFrom(from);
			messageHelper.setTo(to);
			messageHelper.setSubject(subject);
			boolean isHtml=true;
			messageHelper.setText(text,isHtml);
			return mimeMessage;
		} catch (javax.mail.MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * init html mail
	 * @methodDescribe
	 * @param from	发送者
	 * @param to	接收者
	 * @param subject	标题
	 * @param text	内容
	 * @return
	 * @author xianghua.hu
	 * @date 2012-5-13 下午03:30:03
	 */
	public MimeMessage initMimeMailMessageAndAttachment(String from,String to,String subject,String text,ArrayList<SysFile> files){
		MimeMessage  mimeMessage = javaMailSender.createMimeMessage();
		try {
			MimeMessageHelper messageHelper =new MimeMessageHelper(mimeMessage, true, "GB2312");
			messageHelper.setFrom(from);
			messageHelper.setTo(to);
			messageHelper.setSubject(subject);
			boolean isHtml=true;
			messageHelper.setText(text,isHtml);
			
			
			//附件处理
			if( files!=null && files.size() >0 ){
				for(SysFile sysFile:files){
					String fileUrl=sysFile.getFileRealPath();
					String fileName=sysFile.getFileTitle();
					String attachmentFilename=MimeUtility.encodeWord(fileName);
					FileSystemResource file = new FileSystemResource(new File(fileUrl));
					messageHelper.addAttachment(attachmentFilename, file);
				}
			}
			
			return mimeMessage;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return mimeMessage;
	}
	
	/**
	 * init html mail
	 * @methodDescribe
	 * @param from	发送者
	 * @param to	接收者
	 * @param subject	标题
	 * @param text	内容
	 * @return
	 * @author xianghua.hu
	 * @date 2012-5-13 下午03:30:03
	 */
	public MimeMessage initMimeMailMessageAddAttachment(MimeMessage  mimeMessage,String fileUrl,String fileName){
		try {
			
	        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "GB2312");
	        
			String attachmentFilename=MimeUtility.encodeWord(fileName);
			FileSystemResource file = new FileSystemResource(new File(fileUrl));
			messageHelper.addAttachment(attachmentFilename, file);
			//String text="<html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=GB2312\"></head><body><div>你好</div><h1>HTML邮件</h1><h2>包含附件</h2>超链接测试是否可以用，再添加附件以后赋值</body></html>";
			//messageHelper.setText(text, true);
			return mimeMessage;
		} catch (Exception e) {
			System.out.println("附件添加失败！");
			e.printStackTrace();
		}
		return mimeMessage;
        
	}
	
	
	/**
	 * 
	 * @param mimeMessage
	 * @param sysFile
	 * @author huxh
	 * @date 2012-7-3 
	 */
	public MimeMessage initMimeMailMessageAddAttachment(MimeMessage mimeMessage,SysFile sysFile) {
		try {
			String fileUrl=sysFile.getFileRealPath();
			String fileName=sysFile.getFileTitle();
			return initMimeMailMessageAddAttachment(mimeMessage, fileUrl, fileName);
		} catch (Exception e) {
			System.out.println("附件添加失败！");
			e.printStackTrace();
		}
		return mimeMessage;
	}
	
	/**
	 * @methodDescribe
	 * @param args
	 * @author xianghua.hu
	 * @throws MessagingException 
	 * @date 2012-3-14 下午04:26:25
	 */
	public static void main(String[] args) throws MessagingException {
		
		UtilsSendMail uSendMail =new UtilsSendMail();
		String from=null;
		
		String to="huxianghua_java@163.com";
		String subject="线程池-邮件";
		String content="你好，spring mail";
		uSendMail.sendMail(from, to, subject, content);
		
//		Properties props = null;//
//		Authenticator authenticator = null;
//		// 登录邮件服务器，获取会话
//		Session session =Session.getInstance(props, authenticator);
//		
//		Transport transport = session.getTransport();
//		
////		# final MimeMessage message = new MimeMessage(session);  
////		#     // 设置发信人  
////		#     message.setFrom(new InternetAddress(authenticator.getUsername()));  
////		#     // 设置收件人  
////		#     message.setRecipient(RecipientType.TO, new InternetAddress(recipient));  
////		#     // 设置主题  
////		#     message.setSubject(subject);  
////		#     // 设置邮件内容  
////		#     message.setContent(content.toString(), "text/html;charset=utf-8");  
////		#     // 发送  
////		#     Transport.send(message);
//		
//		MimeMessage msg=new MimeMessage(session);
//		Address[] addresses=msg.getAllRecipients();
//		transport.sendMessage(msg, addresses);
	}


	

}
 